package com.sjh;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author jack
 * @data 2020/8/21 6:55 下午
 */
public class ConditionCommunication {
    //子线程循环10次和主线程循环100次， 两者交替运行50次
    public static void main(String[] args) {
        Business business = new Business();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i <= 50; i++) {
                    business.sub(i);
                }
            }
        },"sub").start();

        for (int i = 1; i <= 50; i++) {
            business.main(i);
        }


    }
    static class Business {
        private boolean isShouldMain = true;
        private Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();
        public void main(int num) {
            lock.lock();
            try {
                while (isShouldMain) {
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //循环100次
                for (int i = 1; i <= 100; i++) {
                    System.out.println(String.format("main execute of: %s loop of:%s ", i, num));
                }
                isShouldMain = true;
                condition.signal();
            } finally {
                lock.unlock();
            }
        }

        public void sub(int num) {
           lock.lock();
           try {
               while (!isShouldMain) {
                   try {
                       condition.await();
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
               }
               //循环10次
               for (int i = 1; i <= 10; i++) {
                   System.out.println(String.format(Thread.currentThread().getName() + " execute of: %s loop of:%s ", i, num));
               }
               isShouldMain = false;
               condition.signal();
           } finally {
               lock.unlock();
           }

        }
    }
}

